package com.example.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.ResponseResult;
import com.example.common.dto.LoginDto;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 登录
     * @param loginDto
     * @param response
     * @return
     */
    @PostMapping("login")
    public ResponseResult login(@RequestBody LoginDto loginDto, HttpServletResponse response){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user,"用户不存在"); //为真继续执行，假抛出异常
        if (!user.getPassword().equals( SecureUtil.md5(loginDto.getPassword()))){
            return ResponseResult.fail("密码错误");
        }
        String token = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization",token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        return ResponseResult.success(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                .put("avatar",user.getAvatar())
                .put("email",user.getEmail())
                .map()
                );
    }
    /**
     * 退出
     */
    @RequiresAuthentication
    @GetMapping("logout")
    public ResponseResult logout(){
        SecurityUtils.getSubject().logout();
        return ResponseResult.success(null);
    }


}
